package com.imporven.sell.controller;

import com.imporven.sell.domain.ProductCategory;
import com.imporven.sell.domain.ProductInfo;
import com.imporven.sell.service.ProductCategoryService;
import com.imporven.sell.service.ProductService;
import com.imporven.sell.util.ResultVoUtil;
import com.imporven.sell.vo.ProductDetailVo;
import com.imporven.sell.vo.ProductVo;
import com.imporven.sell.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author imporven
 * @version 1.0.0
 * @date 2018-7-7 21:13
 * 买家商品Controller
 */
@RestController
@RequestMapping("/sell/buyer")
public class BuyerProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/product/list")
    public ResultVo<ProductVo> productList(){

        //1.查找所有商品
        List<ProductInfo> products = productService.findUpAll();

        //2.获取所有类目
        List<Integer> cateGoryNos = products.stream()
                        .map(ProductInfo::getCategoryNo)
                        .collect(toList());
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryNoIn(cateGoryNos);

        //3.组装数据返回
        List<ProductVo> productVos = productCategoryList.stream()
                .map(productCategory -> {
                    ProductVo productVo = new ProductVo();
                    productVo.setCategoryName(productCategory.getCategoryName());
                    productVo.setCategoryNo(productCategory.getCategoryNo());
                    productVo.setProductDetailVos(products.stream()
                            .filter(product -> product.getCategoryNo().equals(productCategory.getCategoryNo()))
                            .map(product -> {
                                ProductDetailVo productDetailVo = new ProductDetailVo();
                                BeanUtils.copyProperties(product,productDetailVo);
                                return productDetailVo; })
                            .collect(toList()));
                    return productVo;
                })
                .collect(toList());

        return ResultVoUtil.success(productVos);
    }

}
